package cn.fcq.ymcc.service.impl;

import cn.fcq.ymcc.domain.Course;
import cn.fcq.ymcc.domain.CourseMarket;
import cn.fcq.ymcc.domain.CourseOrder;
import cn.fcq.ymcc.domain.CourseOrderItem;
import cn.fcq.ymcc.dto.CourseOrderCreateParamsDto;
import cn.fcq.ymcc.dto.KillCourseOrderCreateParamsDto;
import cn.fcq.ymcc.dto.KillPreOrderParamsDto;
import cn.fcq.ymcc.dto.PayDto;
import cn.fcq.ymcc.exception.GlobalException;
import cn.fcq.ymcc.feign.CourseUserLearnFeignClient;
import cn.fcq.ymcc.mapper.CourseOrderMapper;
import cn.fcq.ymcc.result.JSONResult;
import cn.fcq.ymcc.service.ICourseOrderItemService;
import cn.fcq.ymcc.service.ICourseOrderService;
import cn.fcq.ymcc.util.AssertUtil;
import cn.fcq.ymcc.util.CodeGenerateUtils;
import cn.fcq.ymcc.vo.CourseItemVo;
import cn.fcq.ymcc.vo.CourserOrderVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lao.xu
 * @since 2022-08-04
 */
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lao.yang
 * @since 2022-07-29
 */
@Service
@Slf4j
public class CourseOrderServiceImpl extends ServiceImpl<CourseOrderMapper, CourseOrder> implements ICourseOrderService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Autowired
    private CourseUserLearnFeignClient courseInfoForOrderFeignClient;
    @Autowired
    private ICourseOrderItemService courseOrderItemService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private RedissonClient redissonClient;
    /**
     * 1.参数校验
     * 2.token是否有效，如果有效才下单
     * 3.业务校验  课程必须是上架的，课程Id不能重复===
     * 4.保存订单 （主订单-子订单）
     * 4.1 保存主订单  主订单中的总金额是没有
     * 4.2 保存子订单 统计出总金额
     * 4.3 修改主订单金额
     * 5.删除防重复token
     *   我们下单成功，需要及时把redis中的token删除掉，竟可能保证不重复下单
     * @param dto
     */
    @Override
    @Transactional
    public String placeOrder(CourseOrderCreateParamsDto dto) {
        //1.参数校验
        //2.token是否有效，如果有效才下单
        Long loginId = 1L;
        // org.apache.commons.lang.StringUtils  不是Spring下的
        String courseIdsStr = StringUtils.join(dto.getCourseIds(), ",");
        String key = courseIdsStr+":"+loginId;
        Object tokenTmp = redisTemplate.opsForValue().get(key);
        AssertUtil.isNotNull(tokenTmp,"token失效啦，请请重新下单哦！");
        AssertUtil.isEquals(dto.getToken(),tokenTmp.toString(),"token错误，请重新下单！");
        //3.业务校验  课程必须是上架的，课程Id不能重复===
        // 3.1 为service-course编写Feign接口，将上午查询的订单结算页的Vo暴露出来
        // 3.2 service-order 通过Feign接口去调用service-course获取，课程相关的数据
        JSONResult jsonResult = courseInfoForOrderFeignClient.courseOrderInfo(courseIdsStr);
        AssertUtil.isTrue(jsonResult.isSuccess(),"信息错误，下单失败！");
        AssertUtil.isNotNull(jsonResult.getData(),"服务不可达，下单失败！");
        String objStr = JSON.toJSONString(jsonResult.getData());
        CourserOrderVo orderVo = JSONObject.parseObject(objStr,CourserOrderVo.class);
        List<CourseItemVo> courseInfos = orderVo.getCourseInfos();
        AssertUtil.isNotNull(courseInfos,"课程信息有误，下单失败");
        //4.保存订单 先主后子
        //4.1 保存主订单  主订单中的总金额是没有
        Date date = new Date();
        CourseOrder order = new CourseOrder();
        order.setCreateTime(date);
        order.setOrderNo(CodeGenerateUtils.generateOrderSn(loginId));
        order.setStatusOrder(0);
        order.setUserId(loginId);
        order.setVersion(0);
        order.setPayType(dto.getPayType());
        //4.2 保存子订单 统计出总金额
        StringBuilder sb = new StringBuilder();
        sb.append("课程【");
        courseInfos.forEach(courseInfoVo->{
            Course course = courseInfoVo.getCourse();
            CourseMarket courseMarket = courseInfoVo.getCourseMarket();
            CourseOrderItem item = new CourseOrderItem();
            item.setAmount(courseMarket.getPrice());
            item.setCount(1);
            order.setTotalCount(order.getTotalCount() + 1);
            order.setTotalAmount(order.getTotalAmount().add(item.getAmount()));
            sb.append(course.getName()).append(",");
            item.setCreateTime(date);
            item.setCourseId(course.getId());
            item.setCourseName(course.getName());
            item.setCoursePic(course.getPic());
            item.setVersion(order.getVersion());
            item.setOrderNo(order.getOrderNo());
            order.getItems().add(item);
        });
        sb.append("】订单");
        //4.3 修改主订单
        order.setTitle(sb.toString());
        //发布事务消息
        //1.将保存主订单和子订单的操作，交给MQ的事务监听器，需要将主订单和自定传过去
        HashMap<Object, Object> extParam = new HashMap<>();
        extParam.put("userId",loginId);
        extParam.put("courseId",courseIdsStr);
        PayDto payDto = new PayDto(
                order.getTotalAmount(),
                order.getPayType(),
                null,
                order.getOrderNo(),
                order.getUserId(),
                JSON.toJSONString(extParam),
                order.getTitle()
        );
        log.info("发送事务消息");
        //构建消息体
        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(payDto)).build();
        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
                "service-order-producer",
                "course-order-topic:course-order-tag",
                message,  //消息体
                order   //额外参数
        );
        log.info("发送完事务消息--检查事务消息状态");
        LocalTransactionState localTransactionState = transactionSendResult.getLocalTransactionState();
        SendStatus sendStatus = transactionSendResult.getSendStatus();
        if(localTransactionState != LocalTransactionState.COMMIT_MESSAGE || sendStatus != SendStatus.SEND_OK ){
            log.info("校验发送事务消息状态异常");
            throw new GlobalException("下单失败！！");
        }
        //发布支付超时延迟消息=================
        try {
            SendResult sendResult = rocketMQTemplate.syncSend(
                    "paytimeout-topic:paytimeout-tag",//topic:tag
                    MessageBuilder.withPayload(order.getOrderNo()).build(),//消息体
                    2000,//发送延迟消息的超时时间
                    4//延迟等级  如果是30分钟 16
            );
            SendStatus sendStatus1 = sendResult.getSendStatus();
            if(sendStatus1 != SendStatus.SEND_OK){
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //发布延迟消息结束===================
        //5.删除防重复token
        redisTemplate.delete(key);
        return order.getOrderNo();
    }
    @Override
    public void saveOrderAndItems(CourseOrder courseOrder) {
        //查询一下是否已经下过单
        CourseOrder orderTmp = selectOrderByOrderNo(courseOrder.getOrderNo());
        AssertUtil.isNull(orderTmp,"订单已经存在，下单失败！");
        //保存订单
        insert(courseOrder);
        courseOrder.getItems().forEach(item->{
            item.setOrderId(courseOrder.getId());
            courseOrderItemService.insert(item);//保存子订单
        });
    }
    /**
     * 根据订单号查询订单
     * @param orderNo
     * @return
     */
    @Override
    public CourseOrder selectOrderByOrderNo(String orderNo) {
        Wrapper<CourseOrder> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no",orderNo);
        return selectOne(wrapper);
    }

    @Override
    public void payOrder(CourseOrder courseOrder) {
        courseOrder.setStatusOrder(CourseOrder.STATE_PAY_SUCCESS);
        courseOrder.setUpdateTime(new Date());
        updateById(courseOrder);
    }

    @Override
    public void cancelOrder(String orderNo) {
        //去支付宝查询一，看订单是否支付成功
        CourseOrder courseOrder = selectOrderByOrderNo(orderNo);
        AssertUtil.isNotNull(courseOrder,"订单不存在");
        if(courseOrder.getStatusOrder().intValue() != CourseOrder.STATE_PAY_SUCCESS.intValue()){
            courseOrder.setStatusOrder(CourseOrder.STATE_CANCEL);
            updateById(courseOrder);
        }
    }


    /**
     * 1.参数校验
     * 2.token是否有效，如果有效才下单==防重复token校验
     * 3.业务校验  从redis中查询预创订单
     * 4.根据预创订单生成主订单和子订单
     * 5.保存订单 （主订单-子订单）
     * 6.删除防重复token
     * 7.删除redis中的预创订单
     * @param dto
     */
    @Override
    public String killPlaceOrder(KillCourseOrderCreateParamsDto dto) {
        //获取预创订单
        KillPreOrderParamsDto preOrder = (KillPreOrderParamsDto) redisTemplate.opsForValue().get(dto.getOrderNo());
        AssertUtil.isNotNull(preOrder,"秒杀非法！！");

        //2.token是否有效，如果有效才下单 key 是什么
        Long loginId = 1L;
        String key = preOrder.getCourseId()+":"+loginId;
        Object tokenTmp = redisTemplate.opsForValue().get(key);
        AssertUtil.isNotNull(tokenTmp,"token失效，请重新下单！");
        AssertUtil.isEquals(dto.getToken(),tokenTmp.toString(),"token错误!，请重新下单");
        //4.保存订单 （主订单-子订单）
        //4.1 保存主订单  主订单中的总金额是没有
        Date date = new Date();
        CourseOrder order = new CourseOrder();
        order.setCreateTime(date);
        order.setOrderNo(preOrder.getOrderNo());
        order.setStatusOrder(0);
        order.setUserId(preOrder.getUserId());
        order.setVersion(0);
        order.setPayType(dto.getPayType());
        order.setTotalAmount(preOrder.getKillAmount());
        order.setTotalCount(preOrder.getKillCount());
        order.setTitle("秒杀下单："+preOrder.getCourseName());
        //保存订单
        //4.2 保存子订单 统计出总金额
        CourseOrderItem item = new CourseOrderItem();
        //item.setOrderId(order.getId());
        item.setAmount(preOrder.getKillAmount());
        item.setCount(preOrder.getKillCount());
        item.setCreateTime(date);
        item.setCourseId(preOrder.getCourseId());
        item.setCourseName(preOrder.getCourseName());
        item.setCoursePic(preOrder.getCoursePic());
        item.setVersion(order.getVersion());
        item.setOrderNo(order.getOrderNo());
        order.getItems().add(item);//把一个的子订单放入order中
        //发布事务消息=========
        //1.需要将保存主订单和子订单的操作，交给MQ的事务监听器，需要将主订单和自定传过去
        /*
          message: 用来生成t_pay_order 表的数据库--要支付的数据
          arg: 用来传递主订单和子订单信息  交给监听器去保存本地事务
         */
        HashMap<Object, Object> extParam = new HashMap<>();
        extParam.put("userId",loginId);
        extParam.put("courseId",preOrder.getCourseId());
        PayDto payDto = new PayDto(
                order.getTotalAmount(),
                order.getPayType(),
                null,
                order.getOrderNo(),
                order.getUserId(),
                JSON.toJSONString(extParam),
                order.getTitle()
        );
        log.info("发送事务消息");

        //构建消息体
        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(payDto)).build();
        TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
                "service-order-producer",//要和监听器上注解申明的名字一致
                "course-order-topic:course-order-tag",
                message,  //消息体
                order   //额外参数
        );
        log.info("发送完事务消息--检查事务消息状态");
        LocalTransactionState localTransactionState = transactionSendResult.getLocalTransactionState();
        SendStatus sendStatus = transactionSendResult.getSendStatus();
        if(localTransactionState != LocalTransactionState.COMMIT_MESSAGE || sendStatus != SendStatus.SEND_OK ){
            log.info("校验发送事务消息状态异常");
            throw new GlobalException("下单失败！！");
        }
        //发布事务消息结束=========

        //发布支付超时延迟消息=================
        try {
            SendResult sendResult = rocketMQTemplate.syncSend(
                    "paytimeout-topic:paytimeout-tag",//topic:tag
                    MessageBuilder.withPayload(order.getOrderNo()).build(),//消息体
                    2000,//发送延迟消息的超时时间
                    4//延迟等级
            );
            SendStatus sendStatus1 = sendResult.getSendStatus();
            if(sendStatus1 != SendStatus.SEND_OK){
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //发布延迟消息结束===================
        //5.删除防重复token
        redisTemplate.delete(key);
        //6.删除预创订单 支付超时，或者支付成功去删
        return order.getOrderNo();
    }
}
